<template>
  <div class="app-container">
    <!--    <el-row :gutter="20">-->
    <!-- 设备列表 -->
    <!--      <el-col :lg="24" :xs="24">-->
    <div class="toolbar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="分类名称"
            clearable
            style="width: 300px;height: 30px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size='large' @click="handleQuery" :icon='Search'
          >搜索</el-button
          >
          <el-button @click="resetQuery" size='large' :icon='Refresh'>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="toolbar" style='margin-bottom: 10px;'>
      <div>
        <el-button
          size='large'
          type="primary"
          :icon='Plus'
          @click="openDialog('user-form')"
        >新增</el-button
        >
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="pageData"
      :strip='true'
      :border='true'
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        key="id"
        label="分类id"
        align="center"
        prop="id"
        width="100"
      />
      <el-table-column
        key="name"
        label="分类名称"
        align="center"
        prop="name"
        width="200"
      />
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
      />
      <el-table-column
        label="图片"
        align="center"
        prop="pic"
      >
        <template #default="scope">
          <div style="width: 100px;height: 100px;margin: 0 auto">
            <img style="width: 100%;height: 100%;object-fit: cover" :src="scope.row.pic" :alt="scope.row.name" />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            type="success"
            size="large"
            @click="openDialog('user-form', scope.row.id)"
            :icon='Edit'
          >编辑</el-button
          >
          <el-button
            type="warning"
            size="large"
            @click="handleDelete(scope.row.id)"
            :icon='Delete'
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-footer class='footer'>
      <el-pagination
        large
        background
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-count='pagination.pageCount'
        layout='total, prev, pager, next'
        :total='pagination.total'
        class='mt-4'
        style='float: right'
        @change='getPage'
      />
    </el-footer>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="formData.name"
            :disabled="!!formData.id"
            placeholder="请输入课程分类名称"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            autosize
            clearable
            v-model="formData.remark"
            placeholder="请填写备注"
          />
        </el-form-item>
        <el-form-item label="图片" prop="pic">
          <el-upload ref='upload' :before-upload='beforeAvatarUpload' :on-success='handleSuccess' v-model:file-list="uploadFiles"
                     :action="action" list-type="picture-card" :auto-upload="true" :limit='1' :on-exceed='handleExceed'>
            <el-icon><Plus /></el-icon>

            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="imgUrl"  style='height: 100%;' alt="" />
                <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <el-icon><Download /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
              </div>
            </template>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import {
  getCourseCategoryPage,
  getCourseCategoryForm,
  addCourseCategory,
  updateCourseCategory,
  deleteCourseCategory
} from "@/api/course/category";
import { Plus, Delete, Edit, Search, Share, Refresh, ZoomIn } from '@element-plus/icons-vue'
import type { CourseCategory, CourseCategoryForm, CourseCategoryQueryParams, CourseCategoryVO } from '@/api/course/category/types.ts'
import {
  type UploadInstance,
  ElMessageBox,
  ElMessage,
  ElForm,
  type UploadProps,
  type UploadRawFile
} from 'element-plus'
import { ref,onMounted,reactive } from "vue";

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<CourseCategoryQueryParams>({
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0); // 数据总数
const pageData = ref<CourseCategoryVO[]>(); // 分页数据
const pagination = ref({
  currentPage: 1,pageSize: 10,total: 0,pageCount: 1
});
const formItem = reactive({
  id: undefined,
  name: '',
  remark: '',
  pic: '',
})
const imgUrl = ref('')
const imgPath = ref('')
const disabled = ref(false)
const dialogImageUrl = ref()
const dialogVisible = ref()
const action = ref('/dev/api/v1/common/upload')
const baseUrl = import.meta.env.VITE_APP_URL
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const uploadFiles = ref([])
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('只能上传jpg格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('图片不能大于1MB!')
    return false
  }
  return true
}
const handleSuccess = (res,file)=>{
  if(res.code === '00000'){
    imgUrl.value = res.data
    imgPath.value = res.data
    formItem.pic = imgUrl.value
  }
}
const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
  console.log(uploadFile)
  uploadFile.url = ''
  imgUrl.value = ''
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = new Date().valueOf();
  upload.value!.handleStart(file)
}

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

// 表单数据
const formData = reactive<CourseCategoryForm>({
  name: undefined,
  remark: undefined,
  pic: undefined,
});

// 校验规则
const rules = reactive({
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  getPage(queryParams.pageNum,queryParams.pageSize);
}

function getPage(currentPage:number,pageSize :number){
  pagination.value.currentPage = queryParams.pageNum = currentPage || 1;
  pagination.value.pageSize = queryParams.pageSize = pageSize || 10
  loading.value = true;
  getCourseCategoryPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.records;
      total.value = data.total;
      pagination.value.currentPage = data.current
      pagination.value.pageSize = data.size
      pagination.value.total = data.total
      pagination.value.pageCount = data.pages
      queryParams.pageNum = data.current;
      queryParams.pageSize = data.size;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 * @param id 用户ID
 */
async function openDialog(type: string, id?: number) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "user-form") {
    if (id) {
      dialog.title = "修改分类信息";
      disabled.value = true;
      getCourseCategoryForm(id).then(({ data }) => {
        Object.assign(formData, { ...data });
        imgUrl.value = data.pic
      });
    } else {
      dialog.title = "新增分类信息";
    }
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();
    imgUrl.value = ''
    imgPath.value = ''
    uploadFiles.value = []
    formData.id = undefined;
    // formData.status = 1;
  }
}

/** 表单提交 */
const handleSubmit = (() => {
  if (dialog.type === "user-form") {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const id = formData.id;
        console.log('==========================',formData);
        loading.value = true;
        if (id) {
          formData.pic = imgUrl.value;
          updateCourseCategory(formData)
            .then(() => {
              ElMessage.success("修改分类信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          formData.pic = imgPath.value;
          addCourseCategory(formData)
            .then(() => {
              ElMessage.success("新增分类信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
});

/** 删除 */
function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除分类信息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteCourseCategory(id).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>
.toolbar {
padding: 10px 0;
}
<style scoped>
.footer {
  margin-top: 20px;
}
</style>
